<?php
/**
 * 加群小程序客服消息推送
 * 作者：刘单风
 * 最后修改时间：2019-01-24
 * 版权：医库PHP小组
 */
namespace app\groupapi\controller;


use app\model\Wechatgroups;
use MoCommon\Services\HttpBase;
use think\Controller;
use think\facade\Cache;
use think\facade\Config;

class Messagepush extends Controller
{
    //微信token验证
    public function wechatMsg($datatype=0)
    {

//        $echoStr = $_GET["echostr"];
//        //判断是否为认证　
//        if ($echoStr) {
//            $this->checkSignature();
//            echo $echoStr;
//        }else{
//            //否则接收客户发送消息
            $this->responseMsg($datatype);
//        }
        exit();
    }


    //接收和发送消息
    public function responseMsg($datatype)
    {
        //接收来自小程序的客户消息JSON
        $postStr = file_get_contents('php://input');
//        $fh = fopen("weixintoken.txt", 'a') ;
//        fwrite($fh, json_encode($postStr));
//        fclose($fh);
        if (!empty($postStr)) {
            $postArr = json_decode($postStr, true);
            $fromUsername = $postArr['FromUserName'];   //发送者openid
            if ($postArr['MsgType'] == 'event' && $postArr['Event'] == 'user_enter_tempsession') {
                //进入客服操作
                $groupid=$postArr['SessionFrom'];
            } else if ($postArr['MsgType'] == 'miniprogrampage') {
                //发送的小程序卡片客服的进一步操作
                $pagepath=explode("?",$postArr['PagePath']);
                $groupmsg=explode("=",$pagepath[1]);
                $groupid=$groupmsg[1];
            }
            //获取群聊名称
            $groupModel=new Wechatgroups();
            $groupdata=$groupModel->groupDetail($groupid);
            $data = array(
                "touser" => $fromUsername,
                "msgtype" => "link",
                "link" => array(
                    "title" => "欢迎你加入群聊",
                    "description" => "欢迎加入".$groupdata['group_name'].",点击入群",
                    "url" => "https://luckprize.meditool.cn/api/group/detail/$groupid/$datatype",
                    "thumb_url" => "https://luckprize.meditool.cn/static/group_yzh/group_logo.png"
                )
            );
            $json = json_encode($data,JSON_UNESCAPED_UNICODE);

            //获取token
            $access_token=$this->get_access_token($datatype);
            /*
             * POST发送https请求客服接口api
             */
            $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" . $access_token;
            //以'json'格式发送post的https请求
            $result=HttpBase::curlapi($url, $json, 0, 1);
//            $fh = fopen("weixintoken.txt", 'a') ;
//            fwrite($fh, "\r\n\r\n ".json_encode($result));
//            fclose($fh);
        }
        echo "success";
        exit;
    }

    //校验
    public function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = "yizhehui_medicool";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if( $tmpStr == $signature)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function get_access_token($datatype)
    {
        if(empty($datatype)){
            //医者会
            $appid = "wx9c0e102d46b4cb9a";
            $secret = "53980aaf89a27e881a7632603e3f0815";
            $cacheid="wechatgroups_access_token_yizhehui";
        }else{
            //患者会
            $appid = "wx59afb6bdceab6649";
            $secret = "2d9288cba6a1bc0bbe3ce9d2adba9922";
            $cacheid="wechatgroups_access_token_huanzhehui";
        }

        $options = Config::get('app.converse');
        $redis = Cache::init($options);
        // 获取基础 access_token
        $access_token = $redis->get($cacheid);
        if (empty($access_token)) {

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
            $access = HttpBase::curlapi($url, null, 0, 0);
            $access = json_decode($access, true);
            $access_token = $access['access_token'];
            $redis->set($cacheid, $access_token, $access['expires_in'] - 600);
        }
        return $access_token;
    }
}